package com.wwt.blog.imp;

import com.wwt.blog.mapper.TagMapper;
import com.wwt.blog.pojo.Tag;
import com.wwt.blog.service.TagService;
import com.wwt.blog.vo.Result;
import com.wwt.blog.vo.TagVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.springframework.beans.BeanUtils.*;

@Service
public class TagServiceImp implements TagService {
    @Autowired
    TagMapper tagMapper;

    @Override
    //查找文章的标签
    public List<TagVo> findTagsByArticleId(Long articleId) {
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);
        return changeToVo(tags);
    }

    //查找标签被引用最多的标签 限制显示limit个
    @Override
    public Result hotTags(int limit) {
        List<Long> ids = tagMapper.findTagsId(limit);
        if (CollectionUtils.isEmpty(ids)) {  //判断是否存在该类的标签
            return Result.result_success(Collections.emptyList());
        }
        else {
            List<TagVo> tags = tagMapper.findTagByIds(ids);
            return Result.result_success(tags);
        }
        }

    @Override
    public Result findAllTags() {
        List<Tag> tags = tagMapper.selectList(null);
        return Result.result_success(changeToVo(tags));
    }
    //标签ID查询详细信息
    @Override
    public Result findDetailById(Integer tagId) {
        Tag tag = tagMapper.selectById(tagId);
        return Result.result_success(tag);
    }

    private List<TagVo> changeToVo(List<Tag> tags){
        List<TagVo> tagVoList=new ArrayList<>();
        for (Tag tagList:tags){
            tagVoList.add(copy(tagList));
        }
        return tagVoList;
    }
    private TagVo copy(Tag tag){
        TagVo tagVo=new TagVo();
         copyProperties(tag,tagVo);
         tagVo.setId(String.valueOf(tag.getId()));
         return tagVo;
    }
}
